from flask import request, jsonify, session
from services.user_service import UserService


class UserController:
    def __init__(self, user_service: UserService):
        self.user_service = user_service

    def get_users(self):
        """获取所有用户"""
        try:
            users = self.user_service.get_all_users()
            return jsonify({
                'code': 0,
                'data': [user.to_dict() for user in users]
            })
        except Exception as e:
            return jsonify({
                'code': 1,
                'message': str(e)
            }), 500

    def get_user(self, user_id):
        """根据ID获取用户"""
        try:
            user = self.user_service.get_user_by_id(user_id)
            if user is None:
                return jsonify({
                    'code': 1,
                    'message': '用户未找到'
                }), 404
            return jsonify({
                'code': 0,
                'data': user.to_dict()
            })
        except Exception as e:
            return jsonify({
                'code': 1,
                'message': str(e)
            }), 500

    def create_user(self):
        """创建新用户"""
        try:
            data = request.get_json()
            name = data.get('name')
            email = data.get('email')
            password = data.get('password')

            if not name or not email or not password:
                return jsonify({
                    'code': 1,
                    'message': '姓名、邮箱和密码是必需的'
                }), 400

            user = self.user_service.create_user(name, email, password)
            return jsonify({
                'code': 0,
                'data': user.to_dict()
            }), 201
        except ValueError as e:
            return jsonify({
                'code': 1,
                'message': str(e)
            }), 400
        except Exception as e:
            return jsonify({
                'code': 1,
                'message': str(e)
            }), 500

    def update_user(self, user_id):
        """更新用户信息"""
        try:
            data = request.get_json()
            name = data.get('name')
            email = data.get('email')

            if not name or not email:
                return jsonify({
                    'code': 1,
                    'message': '姓名和邮箱是必需的'
                }), 400

            user = self.user_service.update_user(user_id, name, email)
            return jsonify({
                'code': 0,
                'data': user.to_dict()
            })
        except ValueError as e:
            return jsonify({
                'code': 1,
                'message': str(e)
            }), 400
        except Exception as e:
            return jsonify({
                'code': 1,
                'message': str(e)
            }), 500

    def delete_user(self, user_id):
        """删除用户"""
        try:
            self.user_service.delete_user(user_id)
            return jsonify({
                'code': 0,
                'message': '用户删除成功'
            })
        except ValueError as e:
            return jsonify({
                'code': 1,
                'message': str(e)
            }), 404
        except Exception as e:
            return jsonify({
                'code': 1,
                'message': str(e)
            }), 500
            
    def login(self):
        """用户登录"""
        try:
            data = request.get_json()
            email = data.get('email')
            password = data.get('password')

            if not email or not password:
                return jsonify({
                    'code': 1,
                    'message': '邮箱和密码是必需的'
                }), 400

            user = self.user_service.authenticate_user(email, password)
            if user:
                # 将用户信息存储到session中
                session['user_id'] = user.id
                session['user_name'] = user.name
                return jsonify({
                    'code': 0,
                    'data': {
                        'message': '登录成功',
                        'user': user.to_dict()
                    }
                })
            else:
                return jsonify({
                    'code': 1,
                    'message': '邮箱或密码错误'
                }), 401
        except Exception as e:
            return jsonify({
                'code': 1,
                'message': str(e)
            }), 500
    
    def register(self):
        """用户注册"""
        try:
            data = request.get_json()
            name = data.get('name')
            email = data.get('email')
            password = data.get('password')

            if not name or not email or not password:
                return jsonify({
                    'code': 1,
                    'message': '姓名、邮箱和密码是必需的'
                }), 400

            user = self.user_service.create_user(name, email, password)
            return jsonify({
                'code': 0,
                'data': {
                    'message': '注册成功',
                    'user': user.to_dict()
                }
            }), 201
        except ValueError as e:
            return jsonify({
                'code': 1,
                'message': str(e)
            }), 400
        except Exception as e:
            return jsonify({
                'code': 1,
                'message': str(e)
            }), 500
            
    def logout(self):
        """用户登出"""
        session.clear()
        return jsonify({
            'code': 0,
            'data': {
                'message': '登出成功'
            }
        })
            
    def check_login_status(self):
        """检查登录状态"""
        if 'user_id' in session:
            return jsonify({
                'code': 0,
                'data': {
                    'logged_in': True,
                    'user': {
                        'id': session['user_id'],
                        'name': session['user_name']
                    }
                }
            })
        else:
            return jsonify({
                'code': 0,
                'data': {
                    'logged_in': False
                }
            })
            
    def change_password(self, user_id):
        """修改用户密码"""
        try:
            data = request.get_json()
            new_password = data.get('new_password')
            
            if not new_password:
                return jsonify({
                    'code': 1,
                    'message': '新密码是必需的'
                }), 400
                
            user = self.user_service.change_password(user_id, new_password)
            return jsonify({
                'code': 0,
                'data': {
                    'message': '密码修改成功',
                    'user': user.to_dict()
                }
            })
        except ValueError as e:
            return jsonify({
                'code': 1,
                'message': str(e)
            }), 404
        except Exception as e:
            return jsonify({
                'code': 1,
                'message': str(e)
            }), 500